package com.zhanglijie.improve.aqs.share.semaphore.demo;

import java.util.concurrent.Semaphore;

/**
 * @author zhanglijie
 * @version 1.0
 * @since 1.1.0 2022/10/4 0004 16:02
 */
public class UseGuifanDemo {

    /**
     *    1.semaphore.acquire();  和lock.lock()不同，aqs的lock.lock()是放在try外面      semaphore.acquire();需要放在try里面  因为 semaphore.acquire()声明了抛出异常必须捕获
     *    而aqs的互斥锁lock.lock（）没有声明（因为lock.lock()中断后只是做了返回中断标记最后中断标记还原，但是semaphore.acquire()中断是直接抛出异常
     *    2.semaphore.acquire()的是state--  semaphore.release();的是state++操作，所以对try finally还需要改进如下
     *     boolean isInterrupt = false;
     *             try {
     *                 semaphore.acquire();
     *                 isInterrupt = true;
     *                 eat();
     *             } catch (Exception e) {
     *                 e.printStackTrace();
     *             } finally {
     *
     *                 System.out.println(Thread.currentThread()
     *                     .getName() + "将退出吃饭");
     *                 if(isInterrupt) {
     *                     semaphore.release();
     *                 }
     *                 System.out.println(semaphore.availablePermits());
     *             }
     *             这样子state最后的值才会对。
     * @param args
     * @throws InterruptedException
     */



    public static void main(String[] args) throws InterruptedException {
        Semaphore semaphore = new Semaphore(1);
        Runnable task = ()->{
             boolean isInterrupt = false;
            try {
                semaphore.acquire();
                isInterrupt = true;
                eat();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {

                System.out.println(Thread.currentThread().getName() + "将退出吃饭");
                 if(isInterrupt) {
                    semaphore.release();
                 }
                System.out.println(semaphore.availablePermits());
             }
        };

        Thread thread1 = new Thread(task, "thread1");
        Thread thread2 = new Thread(task, "thread2");
        Thread thread3 = new Thread(task, "thread3");



        thread1.start();

        Thread.sleep(1000);
        thread2.start();
        thread3.start();
        thread2.interrupt();
        thread3.interrupt();

    }

    private static void eat() throws InterruptedException {
        System.out.println(Thread.currentThread().getName()+"在吃饭");
        Thread.sleep(2000);
    }
}
